#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <queue>
#include <unordered_set>
#include <unordered_map>
#include <functional>
#include <cmath>
#include <cstring>
using namespace std;

// Definition for singly-linked list.
struct ListNode
{
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

class Solution
{
public:
    ListNode *mergeKLists(vector<ListNode *> &lists)
    {
        priority_queue<tuple<int, ListNode *>> pq;
        for (int i = 0; i < lists.size(); ++i)
        {
            auto list = lists[i];
            if (list)
            {
                pq.push({-list->val, list});
            }
        }
        ListNode head;
        ListNode *tail;
        head.next = tail;
        tail = &head;
        while (!pq.empty())
        {
            auto x = pq.top();
            pq.pop();
            auto [v, node] = x;
            ListNode *nxNode = node->next;
            tail->next = node;
            node->next = nullptr;
            tail = node;
            if (nxNode != nullptr)
            {
                pq.push({-nxNode->val, nxNode});
            }
        }
        return head.next;
    }
};
